package org.jim.server.service.impl;

import org.jim.core.ImPacket;
import org.jim.core.config.ImConfig;
import org.jim.core.packets.ChatBody;
import org.jim.core.packets.ChatType;
import org.jim.core.packets.Command;
import org.jim.core.packets.RespBody;
import org.jim.core.utils.JsonKit;
import org.jim.server.JimServerAPI;
import org.jim.server.config.ImServerConfig;
import org.jim.server.service.IDefultJIMSendService;
import org.jim.server.util.ChatKit;

public class DefultJIMSendServiceImpl implements IDefultJIMSendService {

    @Override
    public Boolean sendToUserBySys(String userId, String msg) {
        ChatBody chatBody = getChatBody(msg, userId, ChatType.CHAT_TYPE_PRIVATE);
        return sendMsg(chatBody,extracted(chatBody));
    }

    @Override
    public Boolean sendToGroupBySys(String groupId, String msg) {
        ChatBody chatBody = getChatBody(msg, groupId, ChatType.CHAT_TYPE_PUBLIC);
        return sendMsg(chatBody,extracted(chatBody));
    }

    @Override
    public Boolean sendByChatBody(ChatBody chatBody) {
        return sendMsg(chatBody,extracted(chatBody));
    }

    @Override
    public Boolean sendByChatBody(String msg) {
        ChatBody chatBody = ChatKit.parseChatBody(msg);
        return sendMsg(chatBody,extracted(chatBody));
    }

    private ImPacket extracted(ChatBody chatBody) {
        ImPacket chatPacket = new ImPacket(Command.COMMAND_CHAT_REQ, new RespBody(Command.COMMAND_CHAT_REQ, chatBody).toByte());
        return chatPacket;
    }

    private ChatBody getChatBody(String msg, String id, ChatType chatTypePublic) {
        ChatBody.Builder createBody = ChatBody.newBuilder()
                .chatType(chatTypePublic.getNumber())
                .from("system")
                .msgType(0)
                .content(msg);
        if (chatTypePublic.equals(ChatType.CHAT_TYPE_PUBLIC)) {
            createBody.groupId(id);
        } else if (chatTypePublic.equals(ChatType.CHAT_TYPE_PRIVATE)) {
            createBody.to(id);
        }
        ChatBody chatBody = ChatKit.parseChatBody(JsonKit.toJSONString(createBody.build()));
        return chatBody;
    }

    final boolean sendMsg(ChatBody chatBody, ImPacket chatPacket) {
        ImServerConfig imServerConfig = ImConfig.Global.get();
        boolean isStore = ImServerConfig.ON.equals(imServerConfig.getIsStore());
        //私聊
        if (ChatType.CHAT_TYPE_PRIVATE.equals(chatBody.getChatTypeByInfo())) {
            if (ChatKit.isOnline(chatBody.getTo(), isStore)) {
                JimServerAPI.sendToUser(chatBody.getTo(), chatPacket);
                //发送成功响应包
                return true;
            } else {
                //用户不在线响应包
                return false;
            }
            //群聊
        } else if (ChatType.CHAT_TYPE_PUBLIC.equals(chatBody.getChatTypeByInfo())) {
            JimServerAPI.sendToGroup(chatBody.getGroupId(), chatPacket);
            //发送成功响应包
            return true;
        }
        return false;
    }
}
